From 3f224cff811e970ad8279c89fffbfd800b85bb64 Mon Sep 17 00:00:00 2001
From: Sebastian Kemper <sebastian_ml@gmx.net>
Date: Sat, 23 Oct 2021 01:23:40 +0200
Subject: [PATCH] core: add support for time64 libcs

libcs are implementing changes to fix the year 2038 issue on 32 bit
platforms (see [1]). musl libc already went ahead and implemented it,
starting with musl-1.2.0 (see [2]).

This commit adds the groundwork for always using the "lld" format when
dealing with time_t and casting the values to be formatted to (long
long). The aim is to be future proof and portable.

Example warning when not using TIME_T_FMT while compiling for a 32 bit
target using a time64 libc:

In file included from auth_identity.c:50:
auth_identity.c: In function 'check_date':
../../core/dprint.h:316:73: warning: format '%ld' expects argument of type 'long int', but argument 11 has type 'time_t' {aka 'long long int'} [-Wformat=]
  316 |                                                         fprintf(stderr, "%2d(%d) %s: %.*s%s%s%s" fmt, \
      |                                                                         ^~~~~~~~~~~~~~~~~~~~~~~~
../../core/dprint.h:340:25: note: in expansion of macro 'LOG_FX'
  340 |                         LOG_FX(facility, level, lname, prefix, _FUNC_NAME_, fmt, ## args)
      |                         ^~~~~~
../../core/dprint.h:346:25: note: in expansion of macro 'LOG_FL'
  346 |                         LOG_FL(facility, level, NULL, prefix, fmt, ## args)
      |                         ^~~~~~
../../core/dprint.h:349:25: note: in expansion of macro 'LOG_FP'
  349 |                         LOG_FP(DEFAULT_FACILITY, (level), LOC_INFO, fmt, ## args)
      |                         ^~~~~~
auth_identity.c:594:17: note: in expansion of macro 'LOG'
  594 |                 LOG(L_INFO, "AUTH_IDENTITY VERIFIER: Outdated date header value (%ld sec)\n", tnow - tmsg + glb_iauthval);
      |                 ^~~

[1] https://sourceware.org/glibc/wiki/Y2038ProofnessDesign
[2] https://musl.libc.org/time64.html

Signed-off-by: Sebastian Kemper <sebastian_ml@gmx.net>

auth_identity: use TIME_T_FMT

Signed-off-by: Sebastian Kemper <sebastian_ml@gmx.net>

cdp: use TIME_T_FMT

Signed-off-by: Sebastian Kemper <sebastian_ml@gmx.net>

db_redis: use TIME_T_FMT

Signed-off-by: Sebastian Kemper <sebastian_ml@gmx.net>

ims_charging: use TIME_T_FMT

Signed-off-by: Sebastian Kemper <sebastian_ml@gmx.net>

ims_dialog: use TIME_T_FMT

Signed-off-by: Sebastian Kemper <sebastian_ml@gmx.net>

ims_icscf: use TIME_T_FMT

Signed-off-by: Sebastian Kemper <sebastian_ml@gmx.net>

ims_registrar_pcscf: use TIME_T_FMT

Signed-off-by: Sebastian Kemper <sebastian_ml@gmx.net>

ims_registrar_scscf: use TIME_T_FMT

Signed-off-by: Sebastian Kemper <sebastian_ml@gmx.net>

ims_usrloc_scscf: use TIME_T_FMT

Signed-off-by: Sebastian Kemper <sebastian_ml@gmx.net>

nat_traversal: use TIME_T_FMT

The size of the time_t destination is unknown as it is depending on the
platform. So we "read into a known-size integer (either int or long
long) and then assign the value to a time_t as a second step" (quote
from [1]).

[1] https://stackoverflow.com/questions/4171478/how-to-read-data-into-a-time-t-variable-using-scanf

Signed-off-by: Sebastian Kemper <sebastian_ml@gmx.net>

xhttp_pi: use TIME_T_FMT

Signed-off-by: Sebastian Kemper <sebastian_ml@gmx.net>
---
 src/core/dprint.h                                  | 2 ++
 src/modules/auth_identity/auth_identity.c          | 2 +-
 src/modules/cdp/routing.c                          | 4 ++--
 src/modules/db_redis/redis_dbase.c                 | 2 +-
 src/modules/ims_charging/ims_ro.c                  | 3 ++-
 src/modules/ims_dialog/dlg_handlers.c              | 2 +-
 src/modules/ims_icscf/scscf_list.c                 | 7 ++++---
 src/modules/ims_registrar_pcscf/notify.c           | 4 ++--
 src/modules/ims_registrar_pcscf/save.c             | 5 +++--
 src/modules/ims_registrar_scscf/registrar_notify.c | 5 +++--
 src/modules/ims_registrar_scscf/save.c             | 2 +-
 src/modules/ims_usrloc_scscf/impurecord.c          | 7 ++++---
 src/modules/nat_traversal/nat_traversal.c          | 5 ++++-
 src/modules/xhttp_pi/xhttp_pi_fnc.c                | 8 ++++----
 14 files changed, 34 insertions(+), 24 deletions(-)

--- a/src/core/dprint.h
+++ b/src/core/dprint.h
@@ -35,6 +35,8 @@
 #include "compiler_opt.h"
 #include "cfg_core.h"
 
+#define TIME_T_FMT "lld"
+#define TIME_T_CAST(x) ((long long)(x))
 
 /** dicover the function name */
 /* C >= 99 has __func__, older gcc versions have __FUNCTION__ */
--- a/src/modules/auth_identity/auth_identity.c
+++ b/src/modules/auth_identity/auth_identity.c
@@ -591,7 +591,7 @@ static int check_date(struct sip_msg* ms
 	}
 
 	if (tnow > tmsg + glb_iauthval) {
-		LOG(L_INFO, "AUTH_IDENTITY VERIFIER: Outdated date header value (%ld sec)\n", tnow - tmsg + glb_iauthval);
+		LOG(L_INFO, "AUTH_IDENTITY VERIFIER: Outdated date header value (%" TIME_T_FMT " sec)\n", TIME_T_CAST(tnow - tmsg + glb_iauthval));
 		return -4;
 	} else
 		LOG(AUTH_DBG_LEVEL, "AUTH_IDENTITY VERIFIER: Date header value OK\n");
--- a/src/modules/cdp/routing.c
+++ b/src/modules/cdp/routing.c
@@ -146,10 +146,10 @@ peer* get_first_connected_route(cdp_sess
 	}
 
 	least_recent_time = peers[0]->last_selected;
-	LM_DBG("peer [%.*s] was last used @ %ld\n", peers[0]->fqdn.len, peers[0]->fqdn.s, peers[0]->last_selected);
+	LM_DBG("peer [%.*s] was last used @ %" TIME_T_FMT "\n", peers[0]->fqdn.len, peers[0]->fqdn.s, TIME_T_CAST(peers[0]->last_selected));
 	p = peers[0];
 	for (j = 1; j < peer_count; j++) {
-		LM_DBG("Peer [%.*s] was last used at [%ld]\n", peers[j]->fqdn.len, peers[j]->fqdn.s, peers[j]->last_selected);
+		LM_DBG("Peer [%.*s] was last used at [%" TIME_T_FMT "]\n", peers[j]->fqdn.len, peers[j]->fqdn.s, TIME_T_CAST(peers[j]->last_selected));
 		if (peers[j]->last_selected < least_recent_time) {
 			least_recent_time = peers[j]->last_selected;
 			p = peers[j];
--- a/src/modules/db_redis/redis_dbase.c
+++ b/src/modules/db_redis/redis_dbase.c
@@ -142,7 +142,7 @@ static int db_redis_val2str(const db_val
             _str->s[_str->len] = '\0';
             break;
         case DB1_DATETIME:
-            LM_DBG("converting datetime value %ld to str\n", VAL_TIME(v));
+            LM_DBG("converting datetime value %" TIME_T_FMT " to str\n", TIME_T_CAST(VAL_TIME(v)));
             _str->s = (char*)pkg_malloc(_str->len);
             if (!_str->s) goto memerr;
             localtime_r(&(VAL_TIME(v)), &_time);
--- a/src/modules/ims_charging/ims_ro.c
+++ b/src/modules/ims_charging/ims_ro.c
@@ -856,7 +856,8 @@ void send_ccr_stop_with_param(struct ro_
         LM_DBG("Final used number of seconds for session is %ld\n", used);
     }
 
-    LM_DBG("Call started at %ld and ended at %ld and lasted %d seconds and so far we have billed for %ld seconds\n", ro_session->start_time, stop_time,
+    LM_DBG("Call started at %" TIME_T_FMT " and ended at %" TIME_T_FMT " and lasted %d seconds and so far we have billed for %ld seconds\n",
+            TIME_T_CAST(ro_session->start_time), TIME_T_CAST(stop_time),
             actual_time_seconds, ro_session->billed + used);
     if (ro_session->billed + used < actual_time_seconds) {
         LM_DBG("Making adjustment by adding %ld seconds\n", actual_time_seconds - (ro_session->billed + used));
--- a/src/modules/ims_dialog/dlg_handlers.c
+++ b/src/modules/ims_dialog/dlg_handlers.c
@@ -1867,7 +1867,7 @@ void internal_print_all_dlg(struct dlg_c
 
     LM_DBG("----------------------------");
     LM_DBG("Dialog h_entry:h_id = [%u : %u]\n", dlg->h_entry, dlg->h_id);
-	LM_DBG("Dialog age: %ld\n", act_time - dlg->init_ts);
+    LM_DBG("Dialog age: %" TIME_T_FMT "\n", TIME_T_CAST(act_time - dlg->init_ts));
     LM_DBG("Dialog call-id: %.*s\n", dlg->callid.len, dlg->callid.s);
     LM_DBG("Dialog state: %d\n", dlg->state);
     LM_DBG("Dialog ref counter: %d\n", dlg->ref);
--- a/src/modules/ims_icscf/scscf_list.c
+++ b/src/modules/ims_icscf/scscf_list.c
@@ -586,15 +586,16 @@ void ims_icscf_timer_routine() {
             sl = l->list;
             while (sl) {
 
-                LM_DBG("INF: Score:[%4d] Start_time [%ld] S-CSCF: <%.*s> \n",
+                LM_DBG("INF: Score:[%4d] Start_time [%" TIME_T_FMT "] S-CSCF: <%.*s> \n",
                         sl->score,
-                        sl->start_time,
+                        TIME_T_CAST(sl->start_time),
                         sl->scscf_name.len, sl->scscf_name.s);
                 time_t now = time(0);
                 time_t time_elapsed = now - sl->start_time;
                 if (time_elapsed > scscf_entry_expiry) {
 
-                    LM_DBG("Scscf entry expired: Time now %ld Start time %ld - elapsed %ld\n", now, sl->start_time, time_elapsed);
+                    LM_DBG("Scscf entry expired: Time now %" TIME_T_FMT " Start time %" TIME_T_FMT " - elapsed %" TIME_T_FMT "\n",
+                            TIME_T_CAST(now), TIME_T_CAST(sl->start_time), TIME_T_CAST(time_elapsed));
                     delete_list = 1; //if any of the entries in this list have expired remove the whole list!
 
                 }
--- a/src/modules/ims_registrar_pcscf/notify.c
+++ b/src/modules/ims_registrar_pcscf/notify.c
@@ -209,8 +209,8 @@ int process_contact(udomain_t * _d, int
             /*TODO_LATEST - put this back */
         } else {//state is active
             //update this contact
-            LM_DBG("This contact: <%.*s> is in state active and is in usrloc so just updating - old expires: %li, new expires: %i which is in %i seconds\n", contact_uri.len, contact_uri.s,
-                    pcontact->expires,
+            LM_DBG("This contact: <%.*s> is in state active and is in usrloc so just updating - old expires: %" TIME_T_FMT ", new expires: %i which is in %i seconds\n", contact_uri.len, contact_uri.s,
+                    TIME_T_CAST(pcontact->expires),
                     expires,
                     expires - local_time_now);
             if (ul.update_pcontact(_d, &ci, pcontact) != 0) {
--- a/src/modules/ims_registrar_pcscf/save.c
+++ b/src/modules/ims_registrar_pcscf/save.c
@@ -223,8 +223,9 @@ static inline int update_contacts(struct
 						}
                                                 //TODO_LATEST replace above
 					} else { //update contact
-						LM_DBG("Updating contact: <%.*s>, old expires: %li, new expires: %i which is in %i seconds\n", c->uri.len, c->uri.s,
-								pcontact->expires-local_time_now,
+						LM_DBG("Updating contact: <%.*s>, old expires: %" TIME_T_FMT ", new expires: %i which is in %i seconds\n",
+								c->uri.len, c->uri.s,
+								TIME_T_CAST(pcontact->expires-local_time_now),
 								expires,
 								expires-local_time_now);
 						ci.reg_state = PCONTACT_REGISTERED;
--- a/src/modules/ims_registrar_scscf/registrar_notify.c
+++ b/src/modules/ims_registrar_scscf/registrar_notify.c
@@ -54,6 +54,7 @@
 #include "../../core/parser/parse_from.h"
 #include "../../core/parser/parse_content.h"
 #include "../../core/parser/parse_uri.h"
+#include "../../core/dprint.h" /* TIME_T_FMT */
 #include <libxml/parser.h>
 
 #include "../../lib/ims/useful_defs.h"
@@ -1517,8 +1518,8 @@ void create_notifications(udomain_t* _t,
             subscription_state.len = 0;
             if (subscription_state.s) {
 
-                sprintf(subscription_state.s, "%.*s%ld", subs_active.len,
-                        subs_active.s, s->expires - act_time);
+                sprintf(subscription_state.s, "%.*s%" TIME_T_FMT, subs_active.len,
+                        subs_active.s, TIME_T_CAST(s->expires - act_time));
                 subscription_state.len = strlen(subscription_state.s);
             }
 
--- a/src/modules/ims_registrar_scscf/save.c
+++ b/src/modules/ims_registrar_scscf/save.c
@@ -545,7 +545,7 @@ static inline int update_contacts_helper
                         LM_DBG("Need to update contact: <%.*s>: "
                                 "q_value [%d],"
                                 "sos: [%d],"
-                                "expires [%ld]\n", chi->uri.len, chi->uri.s, qvalue, sos, expires - time(NULL));
+                                "expires [%" TIME_T_FMT "]\n", chi->uri.len, chi->uri.s, qvalue, sos, TIME_T_CAST(expires - time(NULL)));
 
                         LM_DBG("packing contact information\n");
                         if ((ci = pack_ci(msg, chi, expires, 0)) == 0) {
--- a/src/modules/ims_usrloc_scscf/impurecord.c
+++ b/src/modules/ims_usrloc_scscf/impurecord.c
@@ -244,7 +244,7 @@ void print_impurecord(FILE* _f, impureco
             header = 1;
         }
         fprintf(_f, "\t\twatcher uri: <%.*s> and presentity uri: <%.*s>\n", subscriber->watcher_uri.len, subscriber->watcher_uri.s, subscriber->presentity_uri.len, subscriber->presentity_uri.s);
-        fprintf(_f, "\t\tExpires: %ld\n", subscriber->expires);
+        fprintf(_f, "\t\tExpires: %" TIME_T_FMT "\n", TIME_T_CAST(subscriber->expires));
         subscriber = subscriber->next;
     }
 
@@ -405,8 +405,9 @@ static inline void process_impurecord(im
 				hascontacts = 1;
 			}
 		} else {
-			LM_DBG("\t\tContact #%i - %.*s, Ref [%d] (expires in %ld seconds) (State: %d)\n", 
-					k, ptr->c.len, ptr->c.s, ptr->ref_count, ptr->expires - act_time, ptr->state);
+			LM_DBG("\t\tContact #%i - %.*s, Ref [%d] (expires in %" TIME_T_FMT " seconds) (State: %d)\n",
+					k, ptr->c.len, ptr->c.s, ptr->ref_count,
+					TIME_T_CAST(ptr->expires - act_time), ptr->state);
 			mustdeleteimpu = 0;
 			hascontacts = 1;
 		}
--- a/src/modules/nat_traversal/nat_traversal.c
+++ b/src/modules/nat_traversal/nat_traversal.c
@@ -1707,6 +1707,7 @@ static void restore_keepalive_state(void
 	unsigned h;
 	str host;
 	FILE *f;
+	long long ll_1, ll_2;
 
 	if(!keepalive_state_file)
 		return;
@@ -1724,7 +1725,9 @@ static void restore_keepalive_state(void
 	res = fscanf(f, STATE_FILE_HEADER); // skip header
 
 	while(true) {
-		res = fscanf(f, "%63s %63s %ld %ld", uri, socket, &rtime, &stime);
+		res = fscanf(f, "%63s %63s %" TIME_T_FMT " %" TIME_T_FMT, uri, socket, &ll_1, &ll_2);
+		rtime = ll_1;
+		stime = ll_2;
 		if(res == EOF) {
 			if(ferror(f))
 				LM_ERR("error while reading keepalive state file: %s\n",
--- a/src/modules/xhttp_pi/xhttp_pi_fnc.c
+++ b/src/modules/xhttp_pi/xhttp_pi_fnc.c
@@ -3186,18 +3186,18 @@ int ph_run_pi_cmd(pi_ctx_t* ctx)
 						val_str.len = max_page_len - ctx->reply.body.len;
 						if(db_time2str(values[j].val.time_val,
 									val_str.s, &val_str.len)!=0){
-							LM_ERR("Unable to convert double [%ld]\n",
-								values[j].val.time_val);
+							LM_ERR("Unable to convert double [%" TIME_T_FMT "]\n",
+								TIME_T_CAST(values[j].val.time_val));
 							goto error;
 						}
 						p += val_str.len;
 						ctx->reply.body.len += val_str.len;
 						if(link_on) XHTTP_PI_COPY_2(p,XHTTP_PI_SQUOT_GT,val_str);
 						LM_DBG("   got %.*s[%d]=>"
-							"[%ld][%.*s]\n",
+							"[%" TIME_T_FMT "][%.*s]\n",
 							command->q_keys[j]->len,
 							command->q_keys[j]->s, i,
-							values[j].val.time_val,
+							TIME_T_CAST(values[j].val.time_val),
 							val_str.len, val_str.s);
 						break;
 					default:
